#include <header.h>
#include <iostream>

using std::cout;
using std::endl;

int main()
{
    const char *ip = "127.0.0.1";
    const char *port = "1280";

    //创建socket对象
    int sockfd = socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in sock;
    sock.sin_family = AF_INET;
    sock.sin_port = htons(atoi(port));
    sock.sin_addr.s_addr = inet_addr(ip);

    //绑定端口和ip
    bind(sockfd,(const struct sockaddr*)&sock,sizeof(sock));

    //监听端口
    listen(sockfd,10);

    //创建epoll实例
    int epfd = epoll_create1(0);

    //epoll添加对sockfd事件的监听
    struct epoll_event ev;
    ev.data.fd = sockfd;
    ev.events = EPOLLIN;
    epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&ev);

    struct epoll_event evbuf[100];

    //进入事件循环，不断的对事件进行监听
    while(1)
    {
        int nready = epoll_wait(epfd,evbuf,100,5000);
        if(nready == -1 && errno == EINTR)
        {
            continue;
        }
        else if(nready == -1)
        {
            perror("epoll_wait");
        }
        else if(nready == 0)
        {
            printf("TIME_OUT");
        }
        else
        {
            printf("nready : %d\n",nready);
            for(int i = 0;i < nready;++i)
            {
                int fd = evbuf[i].data.fd;
                if(fd == sockfd)
                {
                    struct sockaddr_in evsock;
                    socklen_t len = sizeof(evsock);

                    int netfd = accept(sockfd,(struct sockaddr *)&evsock,&len);
                    if(netfd<0){
                        perror("accept");
                    }
                    printf("Connect %d\n",netfd);
                }
            }
        }
    }




    return 0;
}

